package com.caishi.lkx.exam.service.impl;

import cn.hutool.core.collection.CollUtil;

import com.caishi.lkx.common.CommonResultCode;
import com.caishi.lkx.exam.mapper.PackageMapper;
import com.caishi.lkx.exam.model.PackageModel;
import com.caishi.lkx.exam.model.PackageSkuModel;
import com.caishi.lkx.exam.service.IPackageService;
import com.caishi.lkx.exam.service.IPackageSkuService;
import com.zzw.common.Wrappers;
import com.zzw.common.entity.IBaseMapper;
import com.zzw.common.exception.BizRuntimeException;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class PackageServiceImpl implements IPackageService {

    @Resource
    private PackageMapper packageMapper;
    @Resource
    private IPackageSkuService packageSkuService;

    @Override
    public IBaseMapper<PackageModel, String> getMapper() {
        return packageMapper;
    }

    @Override
    public Boolean delete(List<String> ids) {
        if (CollUtil.isEmpty(ids)) {
            throw new BizRuntimeException(CommonResultCode.illegalArgument);
        }
        if (ids.size() == 1) {
            return this.delete(ids.get(0));
        }
        ids = ids.stream().distinct().collect(Collectors.toList());
        if (!this.canDelete(ids)) {
            throw new BizRuntimeException(CommonResultCode.dataNotAllowDelete);
        }
        if (getMapper().deleteBatchIds(ids) != ids.size()) {
            throw new BizRuntimeException(CommonResultCode.dataChangeError);
        }
        //同步删除sku
        packageSkuService.deleteByPackageIds(ids);
        return true;
    }

    @Override
    @Transactional
    public Boolean delete(String id) {
        if (!this.canDelete(Collections.singletonList(id))) {
            throw new BizRuntimeException(CommonResultCode.dataNotAllowDelete);
        }
        getMapper().deleteById(id);
        packageSkuService.delete(Wrappers.<PackageSkuModel>lambdaUpdate().eq(PackageSkuModel::getPackageId,id));
        return true;
    }

    @Override
    public List<PackageModel> getPackageByExam(Map<String, Object> params) {
        return packageMapper.getPackageByExam(params);
    }
}
